<script>
import * as utils from '../../../utils/helps';

// 云盘数据源
export default {
  name: 'CloudData',
  data() {
    return {
      //分类树数据源
      categories: [],
      //表格行
      rows: [],
      //表格列
      columns: [
        {
          title: '文件名称',
          key: 'name',
        },
        {
          title: '文件类型',
          key: 'typeName',
        },
        {
          title: '创建时间',
          key: 'createTime',
          render: (h, params) => {
            return h('div', utils.getLocalTime(params.row.createTime));
          },
        },
        {
          title: '操作',
          key: 'action',
          width: 120,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                  },
                  on: {
                    click: () => {
                      this.deleteCloudFile(params);
                    },
                  },
                },
                '删除'
              ),
            ]);
          },
        },
      ],
      //当前分类
      catalog: null,
      //当前分类总记录数
      totalCount: 0,
      //分页大小
      pageSize: 10,
      //上传对话框
      uploadModal: false,
      //上传表单
      formData: {},
      //上传数据
      cloudFile: null,
      //表单验证规则
      ruleValidate: {
        name: [{ required: true, message: ' ', trigger: 'blur' }],
        resourceType: [{ required: true, message: ' ', trigger: 'blur' }],
        file: [{ required: true, message: ' ', trigger: 'blur' }],
      },
      //数据类型
      fileTypes: [],
      //业务数据类型
      busFileTypes: [],
      //GIS数据类型
      gisFileTypes: [],
    };
  },
  async created() {
    //加载云盘根节点
    const data = await this.getNodeData();
    this.categories.push(...data);
    this.loadCloudFile(data);
    //加载上传数据类型
    const types = await api.portal.findResourceType({
      parentId: '1,2',
    });
    this.fileTypes = types.data;
    this.busFileTypes = types.data.filter(p => p.parentId == '1');
    this.gisFileTypes = types.data.filter(p => p.parentId == '2');
  },
  methods: {
    //创建分类树节点
    createNode(h, { root, node, data }) {
      return h(
        'span',
        {
          style: {
            fontSize: '14px',
          },
        },
        [
          h('Icon', {
            props: {
              type: 'ios-folder-outline',
            },
            style: {
              marginRight: '4px',
              fontSize: '14px',
            },
          }),
          data.title,
        ]
      );
    },
    //加载节点数据
    async getNodeData(parentId) {
      const response = await api.portal.getCatalog({
        owner: 1,
        ownerId: '00000000-0000-0000-0000-000000000000',
        parentId: parentId || '0',
      });
      let data = response.data.map(p => {
        let hasChild = p.isChild === 'open';
        return {
          id: p.id,
          title: p.name,
          owner: p.owner,
          ownerId: p.ownerId,
          parentId: p.permId,
          catalogId: p.childId,
          hasChild: hasChild,
          children: hasChild ? [] : null,
          loading: false,
          selected: parentId ? true : false,
          render: this.createNode,
        };
      });
      return data;
    },
    //展开树时加载节点数据
    async loadCatalog(item, callback) {
      const data = await this.getNodeData(item.parentId);
      callback(data);
    },
    //点击树节点时显示分类下的云盘数据
    async loadCloudFile(selections) {
      if (selections.length > 0) {
        this.catalog = selections[0];
        this.refreshCurrentCatalog();
      }
    },
    //获取当前分类分页云盘数据
    async getPagedCloudFile(pageIndex) {
      const response = await api.portal.findResourceList({
        objCondition: {
          catalogId: this.catalog.catalogId,
          userId: this.catalog.ownerId,
        },
        pageIndex: pageIndex,
        pageSize: this.pageSize,
        orderby: 'createTime_desc',
      });
      this.rows = response.data.dataSource;
      return response.data;
    },
    //刷新当前分类云盘数据
    async refreshCurrentCatalog() {
      const data = await this.getPagedCloudFile(1);
      this.totalCount = data.pageInfo.totalCount;
    },
    //删除云盘数据
    deleteCloudFile(e) {
      this.$Modal.confirm({
        title: '删除提示',
        content: '数据删除后不可恢复，您确定要删除吗？',
        onOk: async () => {
          const response = await api.portal.deleteResource([e.row.id]);
          this.refreshCurrentCatalog();
          this.$Message.success('数据删除成功!');
        },
      });
    },
    //重置上传表单
    resetForm() {
      this.$refs.uploadForm.resetFields();
      this.$refs.uploadCtrl.clearFiles();
      this.cloudFile = null;
    },
    //获取上传文件，取消自动上传
    getUploadFile(file) {
      this.cloudFile = file;
      return false;
    },
    //上传文件到云盘并新增为应用资源
    async uploadCloudResource() {
      //表单数据校验
      this.$refs.uploadForm.validate();
      if (this.formData.name == '') {
        this.$Message.warning('文件名称为必填项！');
        return;
      }
      if (this.formData.resourceType == '') {
        this.$Message.warning('文件类型为必选项！');
        return;
      }
      if (this.cloudFile == null) {
        this.$Message.warning('未上传文件！');
        return;
      }
      //上传文件到云盘
      const fileInfo = await this.uploadCloudFile();
      //新增为应用资源
      const resInfo = await this.addCloudResource(fileInfo.data);
      //重新加载表格
      this.refreshCurrentCatalog();
      this.uploadModal = false;
      this.$Message.success('数据上传成功!');
    },
    //上传文件到云盘
    uploadCloudFile() {
      let catalogType = this.formData.resourceType.substr(0, 1);
      let fd = new FormData();
      if (catalogType === '1') {
        //上传业务数据到云盘
        fd.append('file', this.cloudFile);
        return api.portal.uploadServiceDocumentTocloud({ id: this.formData.resourceType }, fd, {
          headers: { 'User-Operation-Info': 'a3UjjlaLC9He' },
        });
      } else if (catalogType === '2') {
        //上传GIS数据到云盘
        fd.append('file', this.cloudFile);
        fd.append('hasparent', '0');
        fd.append('resourcetypeid', this.formData.resourceType);
        return api.portal.uploadDataTocloud({}, fd, {
          headers: { 'User-Operation-Info': 'a3UjjlaLC9He' },
        });
      }
    },
    //新增为应用资源
    addCloudResource(fileInfo) {
      let typeInfo = this.fileTypes.find(p => p.dataTypeId == this.formData.resourceType); //分类信息
      let userInfo = this.$store.state.user.info; //用户信息
      let resource = {
        name: this.formData.name,
        alias: this.formData.alias,
        typeId: this.formData.resourceType,
        typeName: typeInfo.resourceTypeName,
        description: this.formData.description,
        tag: this.formData.tag,
        catalogId: this.catalog.catalogId,
        userId: userInfo.id,
        userName: userInfo.name,
      };
      let postData = Object.assign({}, fileInfo, resource);
      return api.portal.addResource(postData);
    },
  },
};
</script>
<template>
  <div class="cloud-data-wrapper">
    <div class="cloud-pane left-pane">
      <div class="cloud-pane-header">
        <Icon
          type="ios-list"
          size="22"></Icon>
        <span>目录列表</span>
      </div>
      <div class="cloud-pane-content">
        <Tree
          :data="categories"
          :load-data="loadCatalog"
          @on-select-change="loadCloudFile">
        </Tree>
      </div>
    </div>
    <div class="cloud-pane right-pane">
      <div class="cloud-pane-header">
        <Icon
          type="cube"
          size="22"></Icon>
        <span>我的内容</span>
        <div class="cloud-pane-buttons">
          <Button
            type="ghost"
            @click="uploadModal = true">上传</Button>
        </div>
      </div>
      <div class="cloud-pane-content">
        <div class="cloud-table">
          <Table
            :columns="columns"
            :data="rows"
            size="small"
            border
            stripe
            highlight-row>
          </Table>
        </div>
        <div class="cloud-page">
          <Page
            :total="totalCount"
            :page-size="pageSize"
            @on-change="getPagedCloudFile">
          </Page>
        </div>
      </div>
    </div>
    <Modal
      v-model="uploadModal"
      transfer
      width="400px"
      class="cloud-data-modal"
      @on-visible-change="resetForm">
      <Form
        ref="uploadForm"
        :model="formData"
        :label-width="90"
        :rules="ruleValidate"
        class="cloud-upload-form">
        <Form-item
          class="formItem"
          label="名称："
          prop="name">
          <Input
            v-model="formData.name"
            placeholder="请输入名称" />
        </Form-item>
        <Form-item
          class="formItem"
          label="别名："
          prop="alias">
          <Input
            v-model="formData.alias"
            placeholder="请输入别名" />
        </Form-item>
        <Form-item
          class="formItem"
          label="标签："
          prop="tag">
          <Input
            v-model="formData.tag"
            placeholder="请输入标签" />
        </Form-item>
        <Form-item
          class="formItem"
          label="文件类型："
          prop="resourceType">
          <Select v-model="formData.resourceType">
            <Option-group label="业务文件">
              <Option
                v-for="item in busFileTypes"
                :value="item.id"
                :key="item.id">{{ item.resourceTypeName }}</Option>
            </Option-group>
            <Option-group label="GIS数据">
              <Option
                v-for="item in gisFileTypes"
                :value="item.id"
                :key="item.id">{{ item.resourceTypeName }}</Option>
            </Option-group>
          </Select>
        </Form-item>
        <Form-item
          class="formItem"
          label="描述："
          prop="description"
          style="height: 60px;">
          <Input
            v-model="formData.description"
            type="textarea"
            placeholder="描述" />
        </Form-item>
        <Form-item
          class="formItem"
          label="选择文件"
          prop="file">
          <Upload
            ref="uploadCtrl"
            :before-upload="getUploadFile"
            action="#">
            <Button
              type="ghost"
              icon="ios-cloud-upload-outline">上传文件</Button>
          </Upload>
          <span
            v-if="cloudFile"
            class="upload-file-name">{{ cloudFile.name }}</span>
        </Form-item>
      </Form>
      <div slot="header">
        <div>从文件添加数据</div>
      </div>
      <div slot="footer">
        <Button
          type="text"
          @click="uploadModal=false">取消</Button>
        <Button
          type="primary"
          @click="uploadCloudResource">确定</Button>
      </div>
    </Modal>
  </div>
</template>
<style lang="less">
.cloud-data-wrapper {
  position: relative;
  width: 100%;
  height: 100%;
  .cloud-pane {
    position: absolute;
    top: 0;
    bottom: 0;
    border: 1px solid #ddd;
    border-radius: 2px;
    &.left-pane {
      width: 280px;
      left: 0;
    }
    &.right-pane {
      left: 290px;
      right: 0;
    }
  }
  .cloud-pane-header {
    padding: 10px;
    border-bottom: 1px solid #ddd;
    .k-icon {
      position: relative;
      top: 3px;
      margin-right: 2px;
    }
    .cloud-pane-buttons {
      float: right;
      margin: -3px 5px 0 0;
    }
  }
  .cloud-pane-content {
    padding: 10px;
    position: absolute;
    top: 46px;
    right: 0;
    bottom: 0;
    left: 0;
    .cloud-table {
      position: absolute;
      top: 10px;
      right: 10px;
      bottom: 50px;
      left: 10px;
      overflow: auto;
    }
    .cloud-page {
      position: absolute;
      bottom: 15px;
      right: 15px;
    }
  }
}

.cloud-data-modal {
  .k-modal-body {
    padding-left: 5px;
  }
  .cloud-upload-form {
    .k-form-item {
      margin-bottom: 12px;
      &:last-child {
        margin-bottom: 0;
      }
    }
  }
  .k-upload {
    display: inline-block;
  }
  .upload-file-name {
    margin-left: 5px;
    color: #569cd6;
  }
}
</style>
